//
//  ArticleDetail.swift
//  LeGou
//
//  Created by lxm on 2022/8/17.
//

import UIKit
import WebKit
enum ArticleType : Int {
    // 新人教程
    case freshman = 1
    // 服务商权益
    case serviceIntro = 3
    // 用户协议
    case userProtocol = 2
    // 活跃度获得规则
    case activityRules = 4
    // 服务商等级规则
    case serviceLevelRules = 5
    // 关于我们
    case aboutUs = 6
    // 注册服务协议
    case registerProtocol = 7
    // 隐私协议
    case privateProtocol = 8
    // 乐购二维码群
    case wxGroup = 9
    // 新人免单规则
    case newBuy = 14
    // 商城规则
    case mallRule = 15
    // 话费说明
    case phoneRule = 16
    // 联系客服
    case contactService = 17
    // 电费说明
    case powerIntro = 12
    // 红包参与规则
    case redBagJoinRule = 18
    // 推广额度发放规则
    case quotaRule = 19
    // 竞购规则
    case auctionRule = 21
    // 创客说明
    case ckIntro = 22
    // t1说明
    case tLevelIntro = 23
    
}

class ArticleDetail: ZMViewController, WKNavigationDelegate, UIScrollViewDelegate {
    //MARK: --------------------属性--------------------
    var type = ArticleType.freshman
    //MARK: --------------------UI控件--------------------
    lazy var progress: UIProgressView = {
        let progress = UIProgressView(progressViewStyle: .default)
        progress.progressTintColor = UIColor.zm.colorBase()
        progress.trackTintColor = .white
        return progress
    }()
    
    lazy var web: WKWebView = {
        let userContentController = WKUserContentController()
        var webWidth = ""
        if #available(iOS 11.0, *) {
            webWidth = "device-width";
        } else {
            webWidth = String(format: "%.f", UIScreen.main.scale * SCREEN_W)
        }
        var jSString = String(format: "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%@'); document.getElementsByTagName('head')[0].appendChild(meta);", webWidth)

        let wkUserScript = WKUserScript(source: jSString, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        userContentController.addUserScript(wkUserScript)
        let wkWebConfig = WKWebViewConfiguration()
        wkWebConfig.userContentController = userContentController
        wkWebConfig.allowsInlineMediaPlayback = true
        let web = WKWebView(frame: CGRect.zero, configuration: wkWebConfig)
        web.scrollView.showsVerticalScrollIndicator = false
        web.backgroundColor = .white
        web.navigationDelegate = self
        web.scrollView.delegate = self
        web.scrollView.bounces = false
        web.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        return web
    }()
    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        loadDetail()
//        switch type {
//            case .freshman:
//                title = "新人教程"
//        }
    }
    
    //MARK: --------------------UI--------------------
    func setUI() {
        view.addSubview(web)
        
        view.addSubview(progress)
        view.bringSubviewToFront(progress)
        progress.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(2)
        }
    }
    
    func addConstraints() {
        web.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        
    }
    
    func loadDetail() {
        CommonAPI.getDetail(type.rawValue).rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
            let json = JSON(resp)
            self.title = json["title"].stringValue
            self.web.loadHTMLString(json["content"].stringValue.zm.htmlBigSizeString(), baseURL: nil)
        }).disposed(by: disposeBag)
    }

    //MARK: --------------------delegate--------------------
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //  加载进度条
        if keyPath == "estimatedProgress"{
            progress.alpha = 1.0
            progress.setProgress(Float((self.web.estimatedProgress) ), animated: true)
            if (self.web.estimatedProgress )  >= 1.0 {
                UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseOut, animations: {
                    self.progress.alpha = 0
                }, completion: { (finish) in
                    self.progress.setProgress(0.0, animated: false)
                })
            }
        }
    }
    
    // 页面加载完成之后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        /// 获取网页title
//        if webView.title != "" {
//            self.title = webView.title
//        }
    }
}
